package com.itheima.reggie.service.impl;



import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private CartService cartService;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderMapper orderMapper;



    //将某个用户的购物车数据保存成订单数据
    @Override
    public void save(Order order) {
        //获取当前用户
        User user = UserHolder.get();

        //查询当前用户的购物车，如果为空，直接返回错误提示
        List<Cart> cartList = cartService.findList();
        if (CollectionUtil.isEmpty(cartList)) {

            throw new CustomException("购物车数据为空，无法下单");
        }

        //根据提交的addressId，查询用户的收货地址信息，如果不存在，直接返回错误提示
        Address address = addressMapper.selectById(order.getAddressId());
        if (address == null) {
            throw new CustomException("没有收货地址，无法下单");
        }

        //组装订单详情数据，保存订单详情表
        //先确定下订单的主键
        long orderId = IdWorker.getId(); //提供雪花算法

        //组装订单详情
        BigDecimal amount = new BigDecimal(0);//初始金额为0      这个类型为精确金额
        for (Cart cart : cartList) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(cart.getName());//购物车中菜品名称
            orderDetail.setOrderId(orderId);//提前生成
            orderDetail.setDishId(cart.getDishId());//菜品id
            orderDetail.setSetmealId(cart.getSetmealId());//套餐id
            orderDetail.setDishFlavor(cart.getDishFlavor());//菜品口味
            orderDetail.setNumber(cart.getNumber());//菜品数量
            orderDetail.setAmount(cart.getAmount());//金额
            orderDetail.setImage(cart.getImage());//图片

            //叠加金额
            amount = amount.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));

            orderDetailMapper.insert(orderDetail);
        }

        //组装订单数据，保存订单表
        order.setId(orderId);//这个订单的主键是我们自己定义的
        order.setNumber(String.valueOf(orderId));//订单号
        order.setStatus(1);//标识待付款
        order.setUserId(user.getId());//下单用户id
        order.setOrderTime(new Date());//下单时间
        order.setCheckoutTime(new Date());//todo 支付之间，因该是支付的时候才类填这个值
        order.setAmount(amount);//金额
        order.setUserName(user.getName());
        order.setPhone(address.getPhone());//地址中的联系电话
        order.setUserName(user.getName());

        StringBuilder sb = new StringBuilder();//拼接具体地址
        sb.append(StringUtils.isNotEmpty(address.getProvinceName())  ? address.getProvinceName() : "");
        sb.append(StringUtils.isNotEmpty(address.getCityName()) ? address.getCityName() : "");
        sb.append(StringUtils.isNotEmpty(address.getDistrictName()) ? address.getDistrictName() : "");
        sb.append(StringUtils.isNotEmpty(address.getDetail()) ? address.getDetail() : "");
        order.setAddress(sb.toString());//联系地址
        order.setConsignee(address.getConsignee());//地址中取得的练习人名字
        orderMapper.insert(order);

        //注意：：：：：：企业中大多情况下，先一表，再多表，因为多表中会用到一表的主角按

        //清空购物车
        cartService.clean();

    }

    @Override
    public Page<Order> findOrder(String number, Integer pageNum, Integer pageSize , String beginTime, String endTime) {
        //创建条件
        //搜索框模糊查询
        LambdaQueryWrapper<Order> orderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderLambdaQueryWrapper.like(StringUtils.isNotEmpty(number), Order::getNumber, number);
        orderLambdaQueryWrapper.ge(StringUtils.isNotEmpty(beginTime), Order::getOrderTime, beginTime)
                .le(StringUtils.isNotEmpty(endTime), Order::getOrderTime, endTime);
        //分页查询
        Page<Order> page = new Page<>(pageNum, pageSize);
        page = orderMapper.selectPage(page, orderLambdaQueryWrapper);
        return page;
    }

    @Override
    public Page<Order> historyOrNewOrder(Integer page, Integer pageSize) {
//        设置条件
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId,UserHolder.get().getId());
        wrapper.orderByDesc(Order::getOrderTime);
        Page<Order> orderPage = new Page<>(page,pageSize);
        //查询
        orderPage = orderMapper.selectPage(orderPage, wrapper);
        List<Order> pageRecords = orderPage.getRecords();
        //遍历
        for (Order re : pageRecords) {
            LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
            wrapper1.eq(OrderDetail::getOrderId,re.getId());
            //查询
            List<OrderDetail> orderDetails = orderDetailMapper.selectList(wrapper1);
            re.setOrderDetails(orderDetails);
        }
        return orderPage;
    }

    @Override
    public Page<Order> findByPage(Long number, Date beginTime, Date endTime, Integer pageNum, Integer pageSize) {
        //1. 设置分页条件
        Page<Order> page = new Page<>(pageNum, pageSize);

        //2. 设置条件
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(number != null, Order::getId, number);
        wrapper.ge(beginTime != null, Order::getOrderTime, beginTime);
        wrapper.le(endTime != null, Order::getOrderTime, endTime);

        //3. 设置排序(时间倒序)
        wrapper.orderByDesc(Order::getOrderTime);

        //4. 执行查询,得到订单信息
        page = orderMapper.selectPage(page, wrapper);

        //5. 遍历订单列表,得到单个订单
        List<Order> orderList = page.getRecords();
        if (CollectionUtil.isNotEmpty(orderList)) {
            for (Order order : orderList) {
                //6. 根据订单id从详情表获取详情信息
                LambdaQueryWrapper<OrderDetail> wrapper1 = new LambdaQueryWrapper<>();
                wrapper1.eq(OrderDetail::getOrderId, order.getId());
                List<OrderDetail> orderDetailList = orderDetailMapper.selectList(wrapper1);
                order.setOrderDetails(orderDetailList);
            }
        }

        //7. 返回
        return page;
    }


}
